package com.base.system.managedBean;

import java.io.Serializable;
import java.util.List;

import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.operamasks.faces.annotation.Accessible;
import org.operamasks.faces.annotation.Action;
import org.operamasks.faces.annotation.BeforeRender;
import org.operamasks.faces.annotation.Bind;
import org.operamasks.faces.annotation.DataModel;
import org.operamasks.faces.annotation.DefineConverter;
import org.operamasks.faces.annotation.EventListener;
import org.operamasks.faces.annotation.Format;
import org.operamasks.faces.annotation.Inject;
import org.operamasks.faces.annotation.ManagedBean;
import org.operamasks.faces.annotation.ManagedBeanScope;
import org.operamasks.faces.annotation.SelectItems;
import org.operamasks.faces.component.grid.impl.UIDataGrid;
import org.operamasks.faces.user.util.Browser;

import com.base.commonKey.entity.CommonKey;
import com.base.commonKey.entity.CommonKeyType;
import com.base.commonKey.service.ICommonKeyDao;
import com.base.commonKey.service.ICommonKeyService;
import com.base.commons.SpringBeanHolder;
import com.base.security.SecurityConst;

/**
 * 
 * This managed bean is generated automatically
 */
@ManagedBean(name = "system_commonKeyListBean", scope = ManagedBeanScope.SESSION)
@DefineConverter(id = "commonKeyTypeFormatter")
public class CommonKeyListBean implements Serializable {
	private final static Log logger = LogFactory
			.getLog(CommonKeyListBean.class);
	private ICommonKeyDao commonKeyDao = SpringBeanHolder
			.getBean("commonKeyDao");
	private ICommonKeyService commonKeyService = SpringBeanHolder
			.getBean("commonKeyService");
	@Inject
	private FacesContext context;
	@Bind(id = "keywords", attribute = "value")
	private String keywords;

	@Bind(id = "commonKeyGrid", attribute = "binding")
	private UIDataGrid commonKeyGrid;

	@SuppressWarnings("unchecked")
	@DataModel(id = "commonKeyGrid")
	private List<CommonKey> getCommonKeys() {
		if (null != keywords && null != commonKeyType && !"".equals(keywords)
				&& !"".equals(commonKeyType)) {
			return commonKeyDao.findAllByNamedQuery(
					"commonKey.getByValueAndType", keywords, commonKeyType);
		} else if (null != keywords
				&& (commonKeyType == null || "".equals(commonKeyType)))
			return commonKeyDao.findAllByNamedQuery("commonKey.getByKeyValue",
					keywords);
		else if (commonKeyType != null
				&& (keywords == null || "".equals(keywords)))
			return commonKeyDao.findAllByNamedQuery("commonKey.getByKeyType",
					commonKeyType);
		else
			return commonKeyDao.getAll();
	}

	// 配置项类型
	@Accessible
	private SelectItem[] commonKeyType_items = this.getAllCommonKeyType();
	@Bind(id = "commonKeyType")
	@SelectItems(source = "#{this.commonKeyType_items}")
	private String commonKeyType;

	// 得到所有的配置项类型
	private SelectItem[] getAllCommonKeyType() {
		List<CommonKeyType> typeList = commonKeyService.getAllCommonKeyType();
		if (typeList.isEmpty())
			return null;
		SelectItem[] result = new SelectItem[typeList.size()];
		int i = 0;
		for (CommonKeyType type : typeList) {
			result[i++] = new SelectItem(type.getTypeCode(), type.getTypeName());
		}

		return result;
	}

	@BeforeRender
	public void beforeRender(boolean isPostback) {
		logger.debug("Listbean 中的 postBack:" + isPostback);
		if (!isPostback) {
			// data = commonKeyDao.getAll();
			keywords = null;
			commonKeyType = null;
		}
	}

	@Action(id = "query")
	public void query() {
		commonKeyGrid.reload();
	}

	@Action(id = "reset")
	public void reset() {
		keywords = null;
		commonKeyType = null;
		// data = commonKeyDao.getAll();
		commonKeyGrid.reload();
	}

	@Action(id = "editCommonKey")
	public void editCommonKey() {
		if (initSelected()) {
			String url = "/modules/system/editCommonKey.faces";
			url = context.getExternalContext().getRequestContextPath() + url;
			String script = "addCenterLayoutTab('"
					+ SecurityConst.COMMONKEY_EDIT_TAB + "','" + "编辑配置项"
					+ "', '" + url + "')";
			Browser.execClientScript("window.top", script);
		}
	}

	private boolean initSelected() {
		Object[] objs = commonKeyGrid.getSelectedValues();
		// System.out.println("取得的选取值是：" + objs);
		if (objs == null || objs.length == 0) {
			alertNoRecordSelected();
			return false;
		}
		context.getExternalContext().getSessionMap().put(
				SecurityConst.COMMONKEY_SELECT_ROW_DATA, (CommonKey) objs[0]);
		return true;
	}

	private void alertNoRecordSelected() {
		Browser.execClientScript("window.alert('请选择一条记录！');");
	}

	@Action(id = "deleteCommonKey")
	public void deleteCommonKey() {
		Object[] objs = commonKeyGrid.getSelectedValues();
		if (objs == null || objs.length == 0) {
			return;
		}
		commonKeyDao.delete((CommonKey) objs[0]);
		// data.remove((CommonKey) objs[0]);
		commonKeyGrid.reload();
		// Browser.execClientScript("window.alert('删除成功！');");
	}

	@Action(id = "showCommonKey")
	public void showCommonKey() {
		Object[] objs = commonKeyGrid.getSelectedValues();
		if (objs == null || objs.length == 0) {
			alertNoRecordSelected();
			return;
		}
		CommonKey ck = (CommonKey) objs[0];
		Integer ckid = ck.getId();
		String url = "/modules/system/showCommonKey.faces?commonKeyId="
				+ ckid.toString();
		url = context.getExternalContext().getRequestContextPath() + url;
		String script = "addCenterLayoutTab('"
				+ SecurityConst.COMMONKEY_SHOW_TAB + "','" + "查看配置项" + "', '"
				+ url + "')";
		Browser.execClientScript("window.top", script);

	}

	@EventListener("deleteCommonKey")
	private void deleteCommonKeyListener(CommonKey commonKey) {
		// data.remove(commonKey);
	}

	@EventListener("addCommonKey")
	private void addCommonKeyListener(CommonKey commonKey) {
		logger.debug("执行了几次呢？");
		// data.add(commonKey);
	}

	// 显示会议材料的数量
	@Format(id = "keyType")
	public String commonKeyTypeFormat(Object value) {
		if (value instanceof String) {
			CommonKeyType type = commonKeyService
					.getCommonKeyTypeByTypeCode(value.toString());
			if (type != null)
				return type.getTypeName();
			return "";
		}
		return "";

	}

}
